package com.macro.mall.es.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.macro.mall.es.dto.DocSaveDto;
import com.macro.mall.es.service.EsDocService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class EsDocServiceImpl implements EsDocService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;


    @Override
    public void batchInsert(DocSaveDto docSaveDto) {
        //取里面的数据
        List<Map<String, Object>> datas = docSaveDto.getDatas();
        String idField = docSaveDto.getIdField();
        if (CollectionUtils.isEmpty(datas)){
            throw new RuntimeException("文档数据不能为空");
        }
        //创建批量请求对象
        BulkRequest bulkRequest = new BulkRequest();
        //为每个文档构建 IndexRequest
        for (Map<String, Object> data : datas) {
            IndexRequest indexRequest = new IndexRequest();
            //校验是否要自增ID
            if (StringUtils.isEmpty(idField)){
                String idValues = String.valueOf(data.get(idField));
                //手动指定ID
                indexRequest.id(idValues);
            }
            //给Source赋值
            indexRequest.source(data, XContentType.JSON);
            //设置文档内容
            bulkRequest.add(indexRequest);
        }
        // 执行批量操作
        if (bulkRequest.numberOfActions() > 0) {
            try {
                BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
                // 检查是否有失败的操作
                if (bulkResponse.hasFailures()) {
                    // todo 调用删除，删除本批次所有的数据

                    // 处理失败的操作，例如记录日志或抛出异常
                    log.error("批量插入数据失败: " + bulkResponse.buildFailureMessage());
                    throw new RuntimeException("批量插入数据失败");
                }else {
                    log.info("成功批量插入 {} 个文档",bulkResponse.getItems().length);
                }
            } catch (IOException e) {
                // 处理可能的IO异常，例如记录日志或重新抛出异常
                log.error("批量插入数据室 发送异常：{}",e.getMessage(),e);
                throw new RuntimeException("批量插入数据时发生异常",e);
            }
        }else {
            log.error("没有有效文档可供插入");
        }
    }

    @Override
    public void delBatch(DocSaveDto docSaveDto) {
        String indexName = docSaveDto.getIndexName();
        List<Map<String, Object>> datas = docSaveDto.getDatas();
        String idField = docSaveDto.getIdField();
        //判断是否为空
        if (datas == null || datas.isEmpty()) {
            throw new RuntimeException("没有要删除的文档");
        }
        //构建一个批量请求
        BulkRequest bulkRequest = new BulkRequest();
        for (Map<String, Object> data : datas) {
            String idValue = (String) data.get(idField);
            if (idValue!=null){
                bulkRequest.add(new DeleteRequest(indexName, idValue));
            }
        }
        try {
            BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            if (bulk.hasFailures()) {
                throw new RuntimeException("批量删除文档失败："+bulk.buildFailureMessage());
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void updateStatus(DocSaveDto docSaveDto) {
        List<Map<String, Object>> datas = docSaveDto.getDatas();
        if (CollectionUtils.isEmpty(datas)){
            throw new RuntimeException("文档数据不能为空");
        }


    }
}
